package com.lalameow.skintags.api;

import com.google.common.collect.Lists;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.lalameow.skintags.SkinTags;
import com.lalameow.skintags.skin.SkinType;

import java.io.*;
import java.util.List;
import java.util.Map;

/**
 * Author: SettingDust.
 * Date: 2018/5/21.
 */
public class SkinJsonAPI {
    private static JsonObject jsonObject;
    private static final String jsonFile = "skinmap.json";

    public static void init() {
        String json = "";
        try {
            File file = new File(SkinTags.getInstance().getDataFolder(), jsonFile);
            if (!file.exists()) {
                if (file.mkdirs()) {
                    file.createNewFile();
                }
            }
            InputStreamReader reader = new InputStreamReader(SkinTags.getInstance().getResource(jsonFile), "UTF-8");

            StringBuilder builder = new StringBuilder();

            try (BufferedReader input = new BufferedReader(reader)) {
                String line;

                while ((line = input.readLine()) != null) {
                    builder.append(line);
                    builder.append('\n');
                }
            }
            json = builder.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        jsonObject = new JsonParser().parse(json).getAsJsonObject();
    }

    public static List<String> getAvailableType() {
        List<String> types = Lists.newArrayList();
        for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
            types.add(entry.getKey());
        }
        return types;
    }

    public static String getSkin(SkinType type, String name) {
        JsonElement skin = jsonObject.getAsJsonObject(type.toString()).get(name);
        if (skin == null) return null;
        return skin.getAsString();
    }

    public static boolean containsType(String type) {
        for (SkinType skinType : SkinType.values()) {
            if (skinType.toString().equals(type)) {
                return true;
            }
        }
        return false;
    }
}
